import { login, logout, getInfo } from "@/api/user";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { resetRouter, anyRoutes, asyncRoutes, constantRoutes } from "@/router";
import router from "@/router";
const getDefaultState = () => {
  return {
    token: getToken(),
    name: "",
    avatar: "",
    // 服务器返回的菜单信息，[根据不同的角色，返回的标记信息，数组里面的元素是字符串]
    routes: [],
    // 角色信息
    roles: [],
    // 权限按钮信息
    buttons: [],
    // 对比之后项目中已有的异步路由，和服务器返回的标记信息进行对比最终需要展示的信息
    resultAsyncRoutes: [],
    // 用户最终要展示的全部路由
    resultAllRoutes: [],
  };
};

const state = getDefaultState();

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState());
  },
  // 存储token
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  //存储用户信息
  SET_USERINFO(state, userInfo) {
    // 用户名
    state.name = userInfo.name;
    // 用户头像
    state.awatar = userInfo.awatar;
    // 菜单权限标记
    state.routes = userInfo.routes;
    // 按钮权限标记
    state.buttons = userInfo.buttons;
    // 角色
    state.roles = userInfo.roles;
  },
  SET_RESULTASYNCROUTES(state, asyncRoutes) {
    // vuex保存过滤后的异步路由,注意,一个用户需要展示完成路由,常量,异步,任意路由
    //
    const tradeMark = {
      component: () => import("@/views/product/TradeMark"),
      meta: { title: "品牌管理" },
      name: "TradeMark",
      path: "tradeMark",
    };
    asyncRoutes[0].children.unshift(tradeMark);
    // console.log(asyncRoutes);
    // asyncRoutes.push(tradeMark);
    state.resultAsyncRoutes = asyncRoutes;
    // 计算出当前用户所有的路由
    state.resultAllRoutes = constantRoutes.concat(
      state.resultAsyncRoutes,
      anyRoutes
    );
    // 为路由器添加新的路由
    router.addRoutes(state.resultAllRoutes);
  },
};

// 定义一个函数
const computedAsyncRoutes = (asyncRoutes, routes) => {
  //过滤出当前用户【超级管理|普通员工】需要展示的异步路由
  return asyncRoutes.filter((item) => {
    //数组当中没有这个元素返回索引值-1，如果有这个元素返回的索引值一定不是-1
    if (routes.indexOf(item.name) != -1) {
      //递归:别忘记还有2、3、4、5、6级路由
      if (item.children && item.children.length) {
        item.children = computedAsyncRoutes(item.children, routes);
      }
      return true;
    }
  });
};

const actions = {
  // user login
  async login({ commit }, userInfo) {
    // 解构出用户名和密码
    const { username, password } = userInfo;
    const result = await login({
      username: username.trim(),
      password: password,
    });
    if (result.code == 20000) {
      // eslint-disable-next-line quotes
      commit("SET_TOKEN", result.data.token);
      setToken(result.data.token);
      return "ok";
    } else {
      return new Promise.reject(new Error("fail"));
    }
  },

  // get user info
  //获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token)
        .then((response) => {
          //获取用户信息:返回数据包含：用户名name、用户头像avatar、routes[返回的标志:不同的用户应该展示哪些菜单的标记]、roles（用户角色信息）、buttons【按钮的信息：按钮权限用的标记】
          const { data } = response;
          //vuex存储用户全部的信息
          commit("SET_USERINFO", data);
          commit(
            "SET_RESULTASYNCROUTES",
            computedAsyncRoutes(asyncRoutes, data.routes)
          );
          resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token)
        .then(() => {
          removeToken(); // must remove  token  first
          resetRouter();
          commit("RESET_STATE");
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken(); // must remove  token  first
      commit("RESET_STATE");
      resolve();
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
